package com.xbongbong.paas.help.analysis.data;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.CoUserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.parse.data.FormDataLinkDataListServiceImpl;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.SaasFieldConstant;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.VisibleRangeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.service.UserTeamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 无子表单的列表解析
 * @author: wufeng
 * @date: 2018/12/5 9:44
 * @desrcption: 解析数据
 */
@Component
public class FormDataLinkDataListAnalysisDataHelp extends FormDataListAnalysisDataHelp {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataLinkDataListAnalysisDataHelp.class);

    @Resource
    private UserTeamService userTeamService;
    @Resource
    private CoUserService coUserService;
    @Resource
    private FormDataLinkDataListServiceImpl formDataLinkDataListService;

    /**
     * 解析数据
     * @param formDataListVO
     * @throws XbbException
     */
    @Override
    public void analysisDataList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {

        try {
            List<PaasFormDataEntityExt> formDataEsList = formDataListVO.getPaasFormDataESList();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(formDataListVO.getHeadList().size());
            for (FieldAttrEntity item : formDataListVO.getHeadList()) {
                explainMap.put(item.getAttr(), item);
            }
            Integer businessType = formDataListDTO.getBusinessType();
            Boolean isUserTeam = UserTeamEnum.hasTeam(businessType);
            String corpid = formDataListDTO.getCorpid();
            List<Long> dataIdList = new ArrayList<>();
            for(PaasFormDataEntityExt item: formDataEsList) {
                dataIdList.add(item.getDataId());
            }
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> paasCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            if (isUserTeam){
                Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(),subBusinessType);
                userTeamService.getUserIdMap(dataIdList,corpid,businessType,isPublic,mainUserMap,coUserMap);
            } else {
                CoUserListDTO coUserListDTO = new CoUserListDTO(formDataListDTO.getAppId(), formDataListDTO.getFormId(), formDataListDTO.getIdIn(), formDataListDTO.getCorpid());
                coUserListDTO.setFormDataIdIn(dataIdList);
                paasCoUserMap = coUserService.coUserMap(coUserListDTO);
            }

            Set<Object> linkDataSet = new HashSet<>();
            for (PaasFormDataEntityExt paasFormDataEsEntity: formDataEsList){
                JSONObject dataJsonObject = paasFormDataEsEntity.getData();
                if (Objects.isNull(dataJsonObject)) {
                    paasFormDataEsEntity.setData(new JSONObject());
                    continue;
                }
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataListDTO, parseSingleRowDataDTO);
                // 设置创建人
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                    String creatorId = dataJsonObject.getString(CustomerManagementEnum.CREATOR.getAttr());
                    parseSingleRowDataDTO.setCreatorId(creatorId);
                    dataJsonObject.put(CustomerManagementEnum.CREATOR.getAttr(), null);
                } else {
                    parseSingleRowDataDTO.setCreatorId(paasFormDataEsEntity.getCreatorId());
                }
                setOwnerIdAndCoUserId(businessType, dataJsonObject, parseSingleRowDataDTO, paasFormDataEsEntity, mainUserMap, coUserMap, paasCoUserMap);
                // 这里用不到再次渲染负责人和协同人
                dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), null);
                dataJsonObject.put(FieldTypeEnum.COUSERID.getAlias(), null);
                if (XbbRefTypeEnum.hasVisibleRangeBusiness().contains(businessType)) {
                    dataJsonObject.put(VisibleRangeEnum.VISIBLE_DEPT.getAttr(), null);
                    dataJsonObject.put(VisibleRangeEnum.VISIBLE_USER.getAttr(), null);
                }
                parseSingleRowDataDTO.setDataJsonObject(dataJsonObject);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setListFlag(1);
                parseSingleRowDataDTO.setDataId(paasFormDataEsEntity.getDataId());
                ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(parseSingleRowDataVO)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                if (!linkResultDataVO.getLinkDataSet().isEmpty()) {
                    linkDataSet.addAll(linkResultDataVO.getLinkDataSet());
                }
            }
            LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
            linkResultDataVO.setExplainMap(explainMap);
            linkResultDataVO.setUserMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            linkResultDataVO.setDepartmentMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            linkResultDataVO.setLinkDataSet(linkDataSet);
            linkResultDataVO.setFormDataList(formDataEsList);
            linkResultDataVO.setExplainList(formDataListVO.getHeadList());
            if(!linkDataSet.isEmpty()){
                LinkResultDataDTO linkResultDataDTO = new LinkResultDataDTO();
                BeanUtil.copyProperties(formDataListDTO, linkResultDataDTO);
                formDataLinkDataListService.formDataLinkDataGet(linkResultDataDTO, linkResultDataVO);
            }
            formDataListVO.setPaasFormDataESList(linkResultDataVO.getFormDataList());
        } catch (XbbException e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    /**
     * 解析单行数据（表单数据详情和编辑回显都获取了此接口）
     * @param parseSingleRowDataDTO
     * @throws XbbException
     * @return LinkResultDataVO 关联数据和关联查询相关
     */
    @Override
    public ParseSingleRowDataVO parseSingleRowData(ParseSingleRowDataDTO parseSingleRowDataDTO) throws XbbException{
        ParseSingleRowDataVO parseSingleRowDataVO = new ParseSingleRowDataVO();
        Integer businessType = parseSingleRowDataDTO.getBusinessType();
        LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
        Set<Object> linkDataSet = new HashSet<>();
        JSONObject dataJsonObject = parseSingleRowDataDTO.getDataJsonObject();
        try {
            Map<String, FieldAttrEntity> explainMap = parseSingleRowDataDTO.getExplainMap();
            Map<String, Object> linkData = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Iterator iterator = dataJsonObject.keySet().iterator();
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(parseSingleRowDataDTO, handlerExplainDTO);
            if (Objects.equals(parseSingleRowDataDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
                    if (ExplainUtil.invisibleOfScope(entry.getValue(), handlerExplainDTO)) {
                        entry.getValue().setHasJudgeVisible(0);
                    }
                }
            }
            while (iterator.hasNext()) {
                String key = Objects.toString(iterator.next());
                FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                if (fieldAttrEntity == null) {
                    continue;
                }
                // 判断高级规则
                // 审批摘要不判断高级权限
                if (Objects.isNull(parseSingleRowDataDTO.getIsProcess()) || !parseSingleRowDataDTO.getIsProcess()) {
                    if (ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO)) {
                        // 高级不可见
                        dataJsonObject.put(key, null);
                        continue;
                    }
                }
                // 关联数据的解析
                if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType())) {
                    if (Objects.nonNull(dataJsonObject.get(key))
                            && dataJsonObject.get(key) instanceof Number && !Objects.equals(dataJsonObject.get(key), 0)) {
                        linkData.put(key, dataJsonObject.get(key));
                        linkDataSet.add(dataJsonObject.get(key));
                    }
                } else if (FieldTypeEnum.LINK_DATA_MULTI.getType().equals(fieldAttrEntity.getFieldType())
                        && Objects.nonNull(dataJsonObject.get(key)) && (dataJsonObject.get(key) instanceof List)) {
                    JSONArray linkDataArray = dataJsonObject.getJSONArray(key);
                    if (CollectionsUtil.isNotEmpty(linkDataArray)) {
                        if (Objects.nonNull(linkData)) {
                            linkData.put(key, dataJsonObject.get(key));
                        }
                        if (Objects.nonNull(linkDataSet)) {
                            linkDataSet.addAll(linkDataArray);
                        }
                    }
                } else {
                    if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                        SaasFieldConstant saasFieldConstant = new SaasFieldConstant();
                        List<String> fieldList = saasFieldConstant.getFieldMap().get(businessType);
                        if (!fieldList.contains(key)) {
                            dataJsonObject.put(key, null);
                        }
                    } else {
                        // 除了关联数据，其他无需返回
                        dataJsonObject.put(key, null);
                    }
                }
            }
            linkResultDataVO.setLinkDataSet(linkDataSet);
            linkResultDataVO.setLinkData(linkData);
            parseSingleRowDataVO.setLinkResultDataVO(linkResultDataVO);
        } catch (XbbException e) {
            throw e;
        }catch (Exception e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.parseSingleRowData表单单行数据解析出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return parseSingleRowDataVO;
    }




}
